import path from 'path'
// 获取所有子路由
function getChildRoutes(routes) {
  const result = []
  for (const item of routes) {
    if (item.children && item.children.length > 0) {
      result.push(...item.children)
    }
  }

  return result
}
function isNull(data) {
  if (!data) {
    return true
  }
  if (JSON.stringify(data) === '{}') {
    return true
  }
  if (JSON.stringify(data) === '[]') {
    return true
  }
}
// 过滤第一层的路由
export function filterRoutes(routes) {
  // 剔除第一层子路由的合集
  const childrenRoutes = getChildRoutes(routes)
  const result = routes.filter((item) => {
    return !childrenRoutes.find((citem) => {
      return item.path === citem.path
    })
  })

  return result
}
// 生成结构化的路由数据
export function getMenus(routes, basePath = '') {
  const result = []
  for (let i = 0; i < routes.length; i++) {
    // meta 和 children 都为空的路由不处理
    if (isNull(routes[i].meta) && isNull(routes[i].children)) {
      continue
    }
    // meta 为空 但 children 有值
    if (isNull(routes[i].meta) && !isNull(routes[i].children)) {
      result.push(...getMenus(routes[i].children))
      continue
    }
    const reoutePath = path.resolve(basePath, routes[i].path)
    let route = result.find((item) => item.path === reoutePath)
    // meta 有值 但是children 为空

    if (!route) {
      route = {
        ...routes[i],
        path: reoutePath,
        children: []
      }
      if (route.meta.icon && route.meta.title) {
        result.push(route)
      }
    }

    if (routes[i].children && routes[i].children.length > 0) {
      route.children.push(...getMenus(routes[i].children, route.path))
    }
  }

  return result
}
